package com.weilele.leisure.time.bean.db


import com.weilele.mvvm.base.livedata.createStatusListLiveData
import com.weilele.mvvm.base.livedata.data
import com.weilele.mvvm.base.livedata.success
import com.weilele.mvvm.utils.db_litepal.MvvmDb

object CommonDb {
    init {
        initDb()
    }
    private const val DB_VIDEO_NAME = "video"

    fun initDb() {
        MvvmDb.setCurrentDb(
            MvvmDb.DbBean(
                DB_VIDEO_NAME, 1,
                listOf(HistorySearchBean::class.java, HistoryVideoBean::class.java)
            )
        )
    }

    /**
     * 历史搜索
     */
    val historySearchData by lazy { createStatusListLiveData<HistorySearchBean>() }

    fun findAllSearchHistory(isForceFindInDb: Boolean = false): MutableList<HistorySearchBean> {
        if (!isForceFindInDb) {
            val value = historySearchData.data
            if (!value.isNullOrEmpty()) {
                return value
            }
        }
        val results = MvvmDb.dao.findAll(HistorySearchBean::class.java)
        results.sortByDescending { it.searchTime }
        historySearchData.success(results)
        return results
    }

    /**
     * 保存搜索历史
     */
    fun saveSearchHistory(keyword: String) {
        val all = MvvmDb.dao.findAll(HistorySearchBean::class.java)
        var isHave = false
        all.forEach {
            if (it.keyword == keyword) {
                it.searchTime = System.currentTimeMillis()
                it.update(it.dbId)
                isHave = true
            }
        }
        if (!isHave) {
            val new = HistorySearchBean(keyword, System.currentTimeMillis())
            all.add(new)
            new.save()
        }
        all.sortByDescending { it.searchTime }
        historySearchData.success(all)
    }

    /**
     * 删除历史搜索
     * 传入null，删除所有历史搜索
     */
    fun deleteSearchHistory(bean: HistorySearchBean?) {
        if (bean == null) {
            MvvmDb.dao.deleteAll(HistorySearchBean::class.java)
            historySearchData.success(mutableListOf())
        } else {
            bean.delete()
        }
        findAllSearchHistory(true)
    }

    /**
     * 保存观看历史
     */
    fun savePlayVideo(bean: HistoryVideoBean?) {
        bean ?: return
        bean.updateTime = System.currentTimeMillis()
        bean.saveOrUpdate("videoId=?", bean.videoId.toString())
    }

    /**
     * 获取历史记录
     */
    fun getHistoryPlayVideos() = MvvmDb.dao.findAll(HistoryVideoBean::class.java).apply {
        sortByDescending { it.updateTime }
    }

    /**
     * 删除历史记录
     */
    fun deleteHistory(currentData: HistoryVideoBean?) {
        currentData?.delete()
    }
}